package com.ny.zmb.openapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ny.zmb.glxt.entity.PmStore;
import com.ny.zmb.glxt.entity.PmStoreExt;
import com.ny.zmb.glxt.service.IPmStoreService;
import com.ny.zmb.glxt.service.PmStoreExtService;
import com.ny.zmb.openapi.controller.entity.Result;
import com.ny.zmb.openapi.entity.*;
import com.ny.zmb.openapi.service.IPmApiLogService;
import com.ny.zmb.openapi.service.PmRegisterExamineService;
import com.ny.zmb.openapi.service.PmRegisterService;
import com.ny.zmb.openapi.ysutil.base.EYinShengBase;
import com.ny.zmb.openapi.ysutil.from.BizReqJsonCollege.UploadDocumentReqCommandPlus;
import com.ny.zmb.openapi.ysutil.utils.RequestNoUntil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 进件
 *
 * @author ChenZhiZheng
 * @date 20241108
 */
@RequestMapping("ys/register")
@RestController
@CrossOrigin
public class YsRegisterController extends EYinShengBase {
    @Resource
    private IPmApiLogService pmApiLogService;
    @Resource
    private PmRegisterService pmRegisterService;
    @Resource
    private PmRegisterExamineService pmRegisterExamineService;
    @Resource
    private PmStoreExtService pmStoreExtService;
    @Resource
    private IPmStoreService pmStoreService;

    /**
     * 获取资料
     *
     * @return
     */
    @Transactional
    @GetMapping("/getInfo")
    public Result getInfo() {
        PmUserToken token = getUserToken();
        Integer userId = token.getUserId();
        PmRegister pmRegister = pmRegisterService.getInfoByUserId(userId);
        PmRegisterExamine pmRegisterExamine = pmRegisterExamineService.getInfoByUserId(userId);
        PmStore pmStore = pmStoreService.getInfoByUserId(userId);
        PmStoreExt pmStoreExt = pmStoreExtService.getInfoByUserId(userId);
        JSONObject jsonObject = new JSONObject();
        if (pmRegister == null) {
            pmRegister = new PmRegister(userId);
            pmRegisterService.saveOrUpdate(pmRegister);
        }
        if (pmRegisterExamine == null) {
            pmRegisterExamine = new PmRegisterExamine(userId, pmRegister.getOutMerchantNo());
            pmRegisterExamineService.saveOrUpdate(pmRegisterExamine);
        }
        if (pmStore == null) {
            pmStore = new PmStore(userId, pmRegister.getOutMerchantNo());
            pmStoreService.saveOrUpdate(pmStore);
        }
        if (pmStoreExt == null) {
            pmStoreExt = new PmStoreExt(userId);
            pmStoreExt.setStoreId(pmStore.getId());
            pmStoreExtService.saveOrUpdate(pmStoreExt);
        }
        jsonObject.put("register", pmRegister);
        jsonObject.put("registerExamine", pmRegisterExamine);
        jsonObject.put("store", pmStore);
        jsonObject.put("storeExt", pmStoreExt);
        return Result.ok(jsonObject);
    }

    /**
     * 进件资料修改
     *
     * @param obj
     * @return
     */
    @PostMapping(value = "/registerUpdate")
    public Result registerUpdate(@RequestBody PmRegister obj) {
        pmApiLogService.save(new PmApiLog("ys/register/" + "registerUpdate", obj.toString()));
        obj.setNullToEmpty();
        return pmRegisterService.updateById(obj) ? Result.ok(obj) : Result.fail(obj);
    }

    /**
     * 店铺资料修改
     *
     * @param obj
     * @return
     */
    @PostMapping("/storeUpdate")
    public Result storeUpdate(@RequestBody PmStore obj) {
        pmApiLogService.save(new PmApiLog("ys/register/" + "storeUpdate", obj.toString()));
        obj.setNullToEmpty();
        return pmStoreService.updateById(obj) ? Result.ok(obj) : Result.fail(obj);
    }

    /**
     * 店铺资料修改
     *
     * @param obj
     * @return
     */
    @PostMapping("/storeExtUpdate")
    public Result storeExtUpdate(@RequestBody PmStoreExt obj) {
        pmApiLogService.save(new PmApiLog("ys/register/" + "storeExtUpdate", obj.toString()));
        obj.setNullToEmpty();
        if (pmStoreExtService.updateById(obj)) {
            return Result.ok(obj);
        } else {
            return Result.fail(obj);
        }
    }

    /**
     * 进件资料修改
     *
     * @param obj
     * @return
     */


    /**
     * YS图片上传专用
     *
     * @param obj
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value = "registerForFileUpdate", consumes = "multipart/form-data")
    public Result registerForFileUpdate(UploadDocumentReqCommandPlus obj, MultipartFile file) {

        pmApiLogService.save(new PmApiLog("ys/register" + "/" + "registerForFileUpdate", obj.toString()));
        String ossPath = pmRegisterService.fileUploadForOss(file, file.getOriginalFilename());
        if (ossPath == null || ossPath.isEmpty()) {
            return Result.fail("OSS图片上传失败");
        }
        // 优化上传
        String ysPath = pmRegisterService.filePathUploadForYs(file, ossPath, obj);
        if (ysPath == null || ysPath.isEmpty()) {
            return Result.fail("YS图片上传失败");
        }
        PmUserToken userDetailByToken = getUserToken();
        Integer userId = userDetailByToken.getUserId();
        // 店铺附加图片
        Boolean flag1 = pmStoreExtService.infoUpdate(userId, obj, ossPath);
        // 进件图片更新
        Boolean flag2 = pmRegisterService.registerForFileUpdate(userId, obj, ysPath);
        JSONObject result = new JSONObject();
        if (flag1 && flag2) {
            result.put("fileCode", ysPath);
            result.put("ossUrl", ossPath);
            return Result.ok("外部商户号:" + obj.getOutMerchantNo() + " - " + obj.getImgType() + "更新成功", result);
        } else {
            return Result.fail("外部商户号:" + obj.getOutMerchantNo() + " - " + obj.getImgType() + "更新失败", result);
        }
    }

    /**
     * 提交资料
     *
     * @return Result
     */
    @PostMapping("/commitInfoToZMB")
    public Result commitInfoToZMB() {
        PmUserToken token = getUserToken();
        Integer userId = token.getUserId();
        PmRegister pmRegister = pmRegisterService.getInfoByUserId(userId);
        if (pmRegister == null) {
            return Result.fail("进件资料未找到");
        }
        pmApiLogService.save(new PmApiLog("ys/register/" + "commitInfo", pmRegister.toString()));
        PmRegisterExamine pmRegisterExamine = pmRegisterExamineService.getInfoByUserId(userId);
        if (pmRegisterExamine == null) {
            return Result.fail("进件审核资料未找到");
        }
        pmRegisterExamine.setStatus(3);
        // 提交资料
        return pmRegisterExamineService.updateById(pmRegisterExamine) ? Result.ok("提交成功,待审核", pmRegisterExamine) : Result.fail("提交失败");
    }

    /**
     * 提交到银盛
     *
     * @param obj
     * @param srcMerchantNo
     * @return
     */
    @PostMapping("/commitToYs")
    public Result commitToYs(@RequestBody JSONObject obj, @RequestParam(required = false) String srcMerchantNo) {
        pmApiLogService.save(new PmApiLog("ys/register/" + "commit", obj.toString()));
        // 提交
        return pmRegisterService.commitToYs(obj, srcMerchantNo);
    }

    @PostMapping("queryMerchant")
    public Result queryMerchant(@RequestBody JSONObject obj, @RequestParam(required = false) String srcMerchantNo) {

        PmUserToken userDetailByToken = getUserToken();
        Integer userId = userDetailByToken.getUserId();
        obj.put("userId", userId);
        return Result.ok(pmRegisterService.queryMerchant(obj, srcMerchantNo));
    }


    @GetMapping("getOutMerchantNo")
    public Result getOutMerchantNo() {
        JSONObject object = new JSONObject();
        PmUserToken userDetailByToken = getUserToken();
        Integer userId = userDetailByToken.getUserId();
        PmRegister pmRegister = pmRegisterService.getInfoByUserId(userId);
        PmStore pmStore = pmStoreService.getInfoByUserId(userId);
        PmStoreExt pmStoreExt = pmStoreExtService.getInfoByUserId(userId);
        if (pmRegister == null) {
            pmRegister = new PmRegister(userId, RequestNoUntil.generateNumericTaskNumber());
        }

        if (pmStore != null) {
            object.putAll(JSONObject.parseObject(JSON.toJSONString(pmStore)));
            object.put("pmStoreId", pmStore.getId());
        }
        if (pmStoreExt != null) {
            object.putAll(JSONObject.parseObject(JSON.toJSONString(pmStoreExt)));
            object.put("pmStoreExtId", pmStoreExt.getId());
        }
        object.putAll(JSONObject.parseObject(JSON.toJSONString(pmRegister)));
        return Result.ok(pmRegister.getOutMerchantNo(), object);
    }

    @GetMapping("getByOutMerchantNo")
    public Result getByOutMerchantNo(@RequestParam String outMerchantNo) {
        PmRegister obj = pmRegisterService.getInfoByOutMerchantNo(outMerchantNo);
        return Result.ok(obj == null ? "没有找到该对象" : obj);
    }


    @GetMapping("/getInfoByOutMerchantNo")
    public Result getInfoByOutMerchantNo(@RequestParam String outMerchantNo) {
        PmRegister register = pmRegisterService.getInfoByOutMerchantNo(outMerchantNo);
        PmStoreExt pmStoreExt = pmStoreExtService.getInfoByOutMerchantNo(outMerchantNo);
        PmStore pmStore = pmStoreService.getInfoByOutMerchantNo(outMerchantNo);
        JSONObject result = new JSONObject();
        result.put("register", register);
        result.put("storeExt", pmStoreExt);
        result.put("store", pmStore);
        return Result.ok(result);
    }

    @GetMapping("/getInfoStatus")
    public Result getInfoStatus() {
        PmUserToken userDetailByToken = getUserToken();
        Integer userId = userDetailByToken.getUserId();
        PmStore pmStore = pmStoreService.getInfoByUserId(userId);
        // 判断店铺信息
        if (pmStore == null) {
            return Result.fail("没有找到店铺信息");
        } else {
            if (pmStore.getStatus() != 1) {
                return Result.fail("店铺信息:" + pmStore.judgeStatus());
            }
        }
        // 判断进件信息
        PmRegister pmRegister = pmRegisterService.getInfoByUserId(userId);
        if (pmRegister == null) {
            return Result.fail("没有找到进件信息");
        }
        // 判断进件审核信息
        PmRegisterExamine pmRegisterExamine = pmRegisterExamineService.getInfoByUserId(userId);
        if (pmRegisterExamine == null) {
            return Result.fail("没有找到进件审核信息");
        } else {
            if (pmRegisterExamine.getStatus() != 1) {
                return Result.fail("ZMB进件审核信息:" + pmRegisterExamine.zmbStatusJudge());
            }
            if (pmRegisterExamine.getYsStatus() != 1) {
                return Result.fail("YS进件审核信息:" + pmRegisterExamine.getYsStatus());
            }
        }
        return Result.ok("OK");

    }

    @GetMapping("/getStoreExt")
    public Result getStoreExt() {
        PmUserToken token = getUserToken();
        Integer userId = token.getUserId();
        PmStoreExt pmStoreExt = pmStoreExtService.getInfoByUserId(userId);
        return pmStoreExt != null ? Result.ok(pmStoreExt) : Result.fail("获取失败");
    }

    @PostMapping("/changeStatus")
    public Result changeStatus(@RequestBody JSONObject obj, @RequestParam(required = false) String srcMerchantNo) {
        pmApiLogService.save(new PmApiLog("ys/changeStatus/" + "changeStatus", obj.toString()));
        // 进件资料修改// 提交
        return pmRegisterService.changeStatus(obj);
    }
}
